package com.chenjun.web.controller.sys;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.Constant;
import com.chenjun.common.base.ResultDto;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortByModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.core.auth.encoder.EncodingUtils;
import com.chenjun.core.dao.generator.entity.SysGroup;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.dao.generator.entity.SysUserGroup;
import com.chenjun.core.dao.generator.entity.SysUserRole;
import com.chenjun.core.service.sys.SysGroupService;
import com.chenjun.core.service.sys.SysRoleService;
import com.chenjun.core.service.sys.SysUserGroupService;
import com.chenjun.core.service.sys.SysUserRoleService;
import com.chenjun.core.service.sys.SysUserService;
import com.chenjun.core.vo.sys.UserDto;
import com.chenjun.core.vo.sys.UserRoleBean;
import com.chenjun.web.controller.BaseController;


/**
 * 
 * @Description: 用户控制器
 * @author yanjinyin
 * @date 2017年7月23日 下午3:45:10
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping("user")
public class UserController extends BaseController {

	@Autowired
	private SysUserService 	sysUserService;
	
	@Autowired
	private SysRoleService		sysRoleService;
	
	@Autowired
	private SysGroupService		sysGroupService;
	
	@Autowired
	private SysUserRoleService	sysUserRoleService;
	
	@Autowired
	private SysUserGroupService	sysUserGroupService;
	
//	@Autowired
//	private SysOfficeService	sysOfficeService;
	
//	@Autowired
//	private SysGradesetService sysGradesetService;
	
//	@Autowired
//	private SysAreaService sysAreaService;

	/**
	 * @Description:根据组织ID取用户信息  
	 * @param param
	 * @return
	 * @author dongyibin
	 * @date 2017-9-9 下午4:53:42
	 */
	@RequestMapping(value = "/getGroupUsers")
	@ResponseBody
	public ResultDto getGroupUsers(DataGridModel param) {
		ResultDto rtDto = new ResultDto();
		// 查用户
		param.getParams().put("isDelete", "0");
		param.getParams().put("disabled", "0");
		param.getSortBy().add(new DataGridSortModel("position_level", DataGridSortModel.ASC));
		Pagination data = sysUserService.doPagination(param);
		rtDto.setData(data);
		return rtDto;
	} 
	
	/**
	 * 
	 * @Description: 页面展示
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:40:58
	 */
	@RequestMapping("/list.html")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView("user/list");
		
		DataGridModel dgms = new DataGridModel();
		dgms.setStart(0);
		dgms.setRows(0);
		dgms.getParams().put("isDel",Constant.State.ENABLED.toString());
		
		DataGridModel dgm = new DataGridModel();
		dgm.setRows(0);
		dgm.getParams().put("disabled", Constant.State.ENABLED.toString());
		mv.addObject("roles",sysRoleService.doListByCondition(dgm));
		mv.addObject("groups",sysGroupService.doListByCondition(dgm));
		return mv;
	}
	
	/**
	 * 
	 * @Description: 分页搜索
	 * @param datagrid
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:41:13
	 */
	@RequestMapping(value = "/search")
	@ResponseBody
	public ResultDto list(DataGridSortByModel datagrid) {
		ResultDto rtDto = new ResultDto();
		if(StringUtils.isNoneBlank(datagrid.getSortKey())){
			DataGridSortModel dgsm = new DataGridSortModel(datagrid.getSortKey(), datagrid.getSortOrder());
			datagrid.getSortBy().add(dgsm);
		}
		datagrid.getParams().put("isDelete", "0");
		Pagination data = sysUserRoleService.doUserRolePagination(datagrid);
		rtDto.setData(data);
		return rtDto;
	}

	/**
	 * 
	 * @Description: 编辑页面元素 
	 * @param dto
	 * @param errors
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:41:27
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public ResultDto edit(@Valid UserDto dto,Errors errors)  throws IllegalAccessException, InvocationTargetException{
		ResultDto rtDto = new ResultDto();
		
		//验证
		if (!hanleErrors(rtDto, errors)) { return rtDto; }
	
		DataGridModel dgm = new DataGridModel();
		dgm.getParams().put("userName", dto.getUserName());
		dgm.getParams().put("nid", dto.getId());
		List<SysUser> users = sysUserService.doListByCondition(dgm);
		if(!CollectionUtils.isEmpty(users)){
			rtDto.resultWaring();
			rtDto.setMessage("该帐户名称已经存在");
			return rtDto;
		}		
		dto.setUserType("0");
		dto.setIsDelete(Constant.State.ENABLED.toString());
		int i = sysUserService.createOrUpdate(UserDto.getBeanByDto(dto));
		if(i<=0){
			rtDto.resultError();
			rtDto.setMessage("编辑系统异常");
		}
		return rtDto;
	}

	/**
	 * 
	 * @Description: 删除指定的记录 
	 * @param id
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:41:43
	 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public ResultDto delete(@PathVariable String id) {
		ResultDto rtDto = new ResultDto();
		SysUser record = new SysUser();
		record.setId(id);
		record.setIsDelete(Constant.State.DISABLED.toString());
		int result = sysUserService.createOrUpdate(record);
		if (result <= 0) {
			rtDto.resultError();
			rtDto.setMessage("要删除的记录不存在!");
		}
		// 由于上面是逻辑删除，所以要同步activiti的物理删除
		sysUserService.deleteActivitiData(id);
		return rtDto;
	}

	/**
	 * 
	 * @Description: 根据参数获取信息 
	 * @param id
	 * @return
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:41:57
	 */
	@RequestMapping("/get/{id}")
	@ResponseBody
	public ResultDto get(@PathVariable String id) throws IllegalAccessException, InvocationTargetException {
		ResultDto rtDto = new ResultDto();
		
		SysUser user = sysUserService.get(id);
		UserDto dto = UserDto.getDtoByModel(user);
		dto.setPassword("");
		DataGridModel dgm = new DataGridModel();
		dgm.getParams().put("userId",dto.getId());
		List<SysUserRole> urs = sysUserRoleService.doListByCondition(dgm);
		if(!CollectionUtils.isEmpty(urs)){
			dto.setRoleId(urs.get(0).getRoleId());
		}
		List<SysUserGroup> ugs = sysUserGroupService.doListByCondition(dgm);
		if(!CollectionUtils.isEmpty(ugs)){
			dto.setGroupId(ugs.get(0).getGroupId());
		}
		rtDto.setData(dto);
		return rtDto;
	}
	/**
	 * 
	 * @Description: 跳转到修改密码页面
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:42:08
	 */
	@RequestMapping("/changePassword.html")
	public ModelAndView changePassword() {
		ModelAndView mv = new ModelAndView("user/changePassword");
		return mv;
	}
	
	/**
	 * 
	 * @Description: 修改密码 
	 * @param dto
	 * @param request
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:42:24
	 */
	@RequestMapping("/doChangePassword")
	@ResponseBody
	public ResultDto doChangePassword(UserDto dto,HttpServletRequest request) {
		ResultDto rtDto = new ResultDto();
		SysUser user = sysUserService.get(getLoginUserId());
		if(user==null){
			rtDto.resultWaring();
			rtDto.setMessage("数据校验失败");
			return rtDto;
		}else if(!dto.getPassword().equals(dto.getRepassword())){
			rtDto.resultWaring();
			rtDto.setMessage("两次输入密码不一致");
			return rtDto;
		}else if(!EncodingUtils.getEncodedPwd(dto.getOldPassword()).equals(user.getPassword())){
			rtDto.resultWaring();
			rtDto.setMessage("原密码错误");
			return rtDto;
		}else{
			user.setPassword(dto.getPassword());
			sysUserService.createOrUpdate(user);
			return rtDto;
		}
	}
	
	/**
	 * 
	 * @Description: 修改用户 
	 * @param dto
	 * @param request
	 * @return
	 * @author hasee
	 * @date 2017年7月23日 下午4:42:43
	 */
	@RequestMapping("/editPassword")
	@ResponseBody
	@RequiresPermissions("user:list:base")
	public ResultDto editPassword(UserDto dto,HttpServletRequest request) {
		ResultDto rtDto = new ResultDto();
		SysUser user = null;
		user = sysUserService.get(dto.getId());
		if (user == null) {
			rtDto.resultWaring();
			rtDto.setMessage("未找到该用户");
			return rtDto;
		}
		user.setPassword(dto.getPassword());
		sysUserService.createOrUpdate(user);
		return rtDto;
	}
	/**
	 * 
	 * @Description: 修改用户信息
	 * @return
	 * @author yanjinyin
	 * @date 2017年7月23日 下午4:42:58
	 */
	@RequestMapping("/changeUserInfo.html")
	public ModelAndView changeUserInfo() {
		
		SysUser user = getLoginUser();
		ModelAndView mv = new ModelAndView("user/changeUserInfo");
		if(null != user){
			user = sysUserService.get(user.getId());
		} else {
			mv = new ModelAndView("login");
		}
		DataGridModel param = new DataGridModel();
		param.getParams().put("userId", user.getId());
		List<UserRoleBean> list = sysUserRoleService.dofListByCondition(param);
		
		if (null != list && !list.isEmpty()) {
			mv.addObject("userInfo", user);
			mv.addObject("roleName", list.get(0).getRoleName());
		}
		return mv;
	}
	
	@RequestMapping("/doChangeUserInfo")
	@ResponseBody
	public ResultDto doChangeUserInfo(UserDto dto,HttpServletRequest request) {
		ResultDto rtDto = new ResultDto();
		SysUser user = sysUserService.get(getLoginUserId());
		if(user==null){
			rtDto.resultWaring();
			rtDto.setMessage("数据校验失败");
			return rtDto;
		}
		try {
			int i = sysUserService.editUser(UserDto.getModelByDto(dto));
			if(i != 1){
				rtDto.resultWaring();
				rtDto.setMessage("修改失败");
			} else {
				rtDto.resultSuccess();
			}
		} catch (IllegalAccessException | InvocationTargetException e) {
			rtDto.resultWaring();
			rtDto.setMessage("操作异常");
		}
		
		return rtDto;
	}
	
	@RequestMapping("/changeMobile.html")
	public ModelAndView changeMobile() {
		ModelAndView mv = new ModelAndView("user/changeMobile");
		return mv;
	}
	
//	@RequestMapping("/changeOfficeInfo.html")
//	public ModelAndView changeOfficeInfo() {
//		ModelAndView mv = new ModelAndView("user/changeOfficeInfo");
//		User user = userService.get(getLoginUserId());
//		DataGridModel param = new DataGridModel();
//		if(null != user.getOfficeId()){
//			param.getParams().put("id", user.getOfficeId());
//			List<SysOfficeMo> list = sysOfficeService.selectMoByCondition(param);
//			mv.addObject("office", list.get(0));
//		}
//		
//		DataGridModel dgmo = new DataGridModel();
//		dgmo.getParams().put("is_delete",Constant.State.ENABLED.toString());
//		dgmo.setRows(0);
//		mv.addObject("gardes",sysGradesetService.doListByCondition(dgmo));
//		
//		DataGridModel dgma = new DataGridModel();
//		dgma.getParams().put("isDelete",Constant.State.ENABLED.toString());
//		dgma.setRows(0);
//		mv.addObject("areas", sysAreaService.doListByCondition(dgma));
//		return mv;
//	}

//	@RequestMapping("/doChangeOfficeInfo")
//	@ResponseBody
//	public ResultDto doChangeOfficeInfo(SysOfficeDto dto, HttpServletRequest request) {
//		ResultDto rtDto = new ResultDto();
//		User user = getLoginUser();
//		if(dto != null && !StringUtil.isNull(dto.getRegisterTime())){
//			dto.setRegisterDate(DateUtil.parseLongStringToDate(dto.getRegisterTime()));
//		} 
//		
//		int i = 0;
//		try {
//			i = sysOfficeService.createOrUpdate(SysOfficeDto.getModelByDto(dto), dto.getOfficeAreaIds(), user.getId());
//		} catch (IllegalAccessException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (InvocationTargetException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		if(i<=0){
//			rtDto.resultError();
//			rtDto.setMessage("编辑系统异常");
//		}
//		return rtDto;
//	}
	
	@RequestMapping("/getParentGroupAndUsers")
	@ResponseBody
	public List<Map<String, Object>> getParentGroupAndUsers(){
		List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
		DataGridModel dgm = new DataGridModel();
		dgm.getParams().put("userId",getLoginUserId());
		List<SysUserGroup> ugs = sysUserGroupService.doListByCondition(dgm);
		if(!CollectionUtils.isEmpty(ugs)){
			String userGroupId = ugs.get(0).getGroupId();
			SysGroup userGroup = sysGroupService.get(userGroupId);
			String[] parentGroupIds = StringUtils.split(userGroup.getParentIds(), ",");
			for(String id : parentGroupIds){
				SysGroup group = sysGroupService.get(id);
				dgm.getParams().remove("userId");
				dgm.getParams().put("groupId", id);
				List<SysUserGroup> sugs = sysUserGroupService.doListByCondition(dgm);
				for(SysUserGroup ug : sugs){
					String userId = ug.getUserId();
					SysUser user = sysUserService.get(userId);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("user", user);
					map.put("group", group);
					result.add(map);
				}
			}
		}
		return result;
	}
}
